package cn.com.longfuinfo.wx;

import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.google.common.collect.Maps;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.ext.handler.UrlSkipHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.AnsiSqlDialect;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.render.ViewType;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

import cn.com.longfuinfo.wx.dao.AdSeller;
import cn.com.longfuinfo.wx.controller.CartController;
import cn.com.longfuinfo.wx.controller.GoodsController;
import cn.com.longfuinfo.wx.controller.OrderController;
import cn.com.longfuinfo.wx.controller.OrderPayNotifyController;
import cn.com.longfuinfo.wx.controller.SynchronizationDate;
import cn.com.longfuinfo.wx.controller.SystemController;
import cn.com.longfuinfo.wx.controller.UserController;
import cn.com.longfuinfo.wx.controller.post.PostRestController;
import cn.com.longfuinfo.wx.dao.Ad;
import cn.com.longfuinfo.wx.dao.BabyTitle;
import cn.com.longfuinfo.wx.dao.Category;
import cn.com.longfuinfo.wx.dao.Feedback;
import cn.com.longfuinfo.wx.dao.GoodSpec;
import cn.com.longfuinfo.wx.dao.Goods;
import cn.com.longfuinfo.wx.dao.Keyword;
import cn.com.longfuinfo.wx.dao.Order;
import cn.com.longfuinfo.wx.dao.OrderList;
import cn.com.longfuinfo.wx.dao.OrderPayAPIRecord;
import cn.com.longfuinfo.wx.dao.OrderRefund;
import cn.com.longfuinfo.wx.dao.OrderRefundAPIRecord;
import cn.com.longfuinfo.wx.dao.Recharge;
import cn.com.longfuinfo.wx.dao.Store;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.UserCollection;
import cn.com.longfuinfo.wx.dao.UserInfo;
import cn.com.longfuinfo.wx.dao.UserLook;
import cn.com.longfuinfo.wx.dao.UserMess;
import cn.com.longfuinfo.wx.dao.UserMoney;
import cn.com.longfuinfo.wx.dao.UserValueLog;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.dao.HomeBag;
import cn.com.longfuinfo.wx.handler.ContextParamsHandler;
import cn.com.longfuinfo.wx.interceptor.AuthLocationInterceptor;
import cn.com.longfuinfo.wx.interceptor.OAuthInterceptor;
import cn.com.longfuinfo.wx.interceptor.TestInterceptor;

public class Config extends JFinalConfig {
	private Logger logger = Logger.getLogger(getClass());
	
	public void configConstant(Constants me) {
		// 如果生产环境配置文件存在，则优先加载该配置，否则加载开发环境配置文件
		//String config = "config.properties";//贝恩正式服务器
		//String config = "config.server.properties";//贝恩测试服务器
		String config = "config.local.properties";//本地 
		
		loadPropertyFile(config);
		//装载进PropKit中
		PropKit.use(config);
		//设置视图根目录
		me.setBaseViewPath("/WEB-INF/page");
	    //设置字符集
	    me.setEncoding("UTF-8");
	    me.setViewType(ViewType.JSP);
	    //调试模式，会打印详细日志
		me.setDevMode(getPropertyToBoolean("constants.devMode", false));
		//出错跳转页面
		me.setError401View("/WEB-INF/page/401.jsp");
		me.setError403View("/WEB-INF/page/403.jsp");
		me.setError404View("/WEB-INF/page/404.jsp");
		me.setError500View("/WEB-INF/page/500.jsp");
	}
	
	public void configRoute(Routes me) {
		me.add("/", SystemController.class);
		me.add("/goods", GoodsController.class);
		me.add("/my", UserController.class);
		me.add("/cart", CartController.class);
		me.add("/order", OrderController.class);
		me.add("/notify", OrderPayNotifyController.class);
		//产后恢复计划
		me.add("/post/rest", PostRestController.class);
	}
	
	public void configPlugin(Plugins me) {
		//缓存
		EhCachePlugin ecp = new EhCachePlugin();
		me.add(ecp);
		
		
		// 配置C3p0数据库连接池插件
		C3p0Plugin c3p0Plugin = new C3p0Plugin(getProperty("db.jdbcUrl"), getProperty("db.username"), getProperty("db.password"), getProperty("db.jdbcDriver"));
		c3p0Plugin.setMaxPoolSize(getPropertyToInt("db.maxPoolSize"));
		c3p0Plugin.setMinPoolSize(getPropertyToInt("db.minPoolSize"));
		c3p0Plugin.setInitialPoolSize(getPropertyToInt("db.initialPoolSize"));
		c3p0Plugin.setMaxIdleTime(getPropertyToInt("db.maxIdleTime"));
		c3p0Plugin.setAcquireIncrement(getPropertyToInt("db.acquireIncrement"));
		me.add(c3p0Plugin);
		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		arp.setDialect(new MysqlDialect());
		//忽略大小写
		//arp.setContainerFactory(new CaseInsensitiveContainerFactory());
		arp.setShowSql(true);
		me.add(arp);
	
		
	
		
		//添加model映射
		//轮播图
		arp.addMapping("t_bus_ad", Ad.class);
		
		//搜索关键字
		arp.addMapping("t_dict_keyword", Keyword.class);
		//用户表
		arp.addMapping("t_bus_user", User.class);
		arp.addMapping("t_bus_user_wx", WxUser.class);
		arp.addMapping("t_auth_admin_seller", AdSeller.class);
		//用户收藏表
		arp.addMapping("t_bus_user_collection", UserCollection.class);
		arp.addMapping("t_bus_goods_look", UserLook.class);
		//用户
		arp.addMapping("t_bus_user_info", UserInfo.class);
		arp.addMapping("t_bus_user_value_log", UserValueLog.class);
		arp.addMapping("t_bus_user_mess", UserMess.class);
		arp.addMapping("t_bus_user_money", UserMoney.class);
		arp.addMapping("t_bus_user_recharge", Recharge.class);
		//商品分类
		arp.addMapping("t_dict_category", Category.class);
		//店铺商品表
		arp.addMapping("t_bus_goods", Goods.class);
		arp.addMapping("t_dict_store", Store.class);
		arp.addMapping("t_bus_goods_spec", GoodSpec.class);//商品规格
		arp.addMapping("t_bus_goods_base_baby_title", BabyTitle.class);
		//商品订单系列
		arp.addMapping("t_bus_order", Order.class);
		arp.addMapping("t_bus_order_apirecord", OrderPayAPIRecord.class);
		arp.addMapping("t_bus_order_refund", OrderRefund.class);
		arp.addMapping("t_bus_order_refund_apirecord", OrderRefundAPIRecord.class);
		arp.addMapping("t_bus_order_list", OrderList.class);
		//建议或反馈
		arp.addMapping("t_sys_feedback", Feedback.class);
		//首页礼包
		arp.addMapping("t_bus_home_window", HomeBag.class);
	
	
	}
	
	public void configInterceptor(Interceptors me) {
		me.add(new SessionInViewInterceptor());
		if(getPropertyToBoolean("constants.devMode", false)){
			//测试用，默认初始化登录信息
			me.add(new TestInterceptor());
		}else{
			//微信授权拦截器
			//注：拦截器放在这里，是防止session在30分钟后失效时，用户可能停留在任意页面
			me.add(new OAuthInterceptor());
			//拦截判断用户是否定位或选择过店铺，如果没有，则跳转至定位页面
			me.add(new AuthLocationInterceptor());
		}
	}
	
	public void configHandler(Handlers me) {
		//可在此设置context_path，解决http://ip:port/context_path的问题
		//因为测试时是在jetty下，所以默认没有context_path，如果部署在tomcat下，会自动加上项目名，所以会用到该配置
		//可自定义context_path，默认下是CONTEXT_PATH，使用如：${CONTEXT_PATH}
		me.add(new ContextPathHandler("BASE_PATH"));
		//需要在页面传递的常量
		Map<String,Object> params = Maps.newHashMap();
		params.put("FTP_PATH", PropKit.get("constants.ftppath"));
		me.add(new ContextParamsHandler(params));
		me.add(new UrlSkipHandler("/wxServlet", true));
	}
	
	@Override
	public void afterJFinalStart() {
		super.afterJFinalStart();
		logger.error("初始化微信api参数");
		//初始化时缓存公众号参数
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("wx.token"));
		ac.setAppId(PropKit.get("wx.appId"));
		ac.setAppSecret(PropKit.get("wx.appSecret"));
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		//ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		//ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		// 将 ApiConfig 对象与当前线程绑定，以便在后续操作中方便获取该对象： ApiConfigKit.getApiConfig();
		ApiConfigKit.setDevMode(PropKit.getBoolean("constants.devMode", false));
		ApiConfigKit.setApiConfig(ac);
		//定时任务 
		SynchronizationDate task = new SynchronizationDate();
		ScheduledThreadPoolExecutor taskScheduler = new ScheduledThreadPoolExecutor(1);
	        if(!PropKit.getBoolean("constants.devMode")){
	        	//taskScheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
	          }
	}
}
